﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SearchTextFiles
{
    class SearchTextFiles
    {
        static void Main(string[] args)
        {
            string searchedDirectory = "../../Test";
            StreamWriter writer = new StreamWriter("../../result.txt");
            using (writer)
            {
                SearchDirectory(searchedDirectory, writer);
            }
        }

        private static void SearchDirectory(string searchedDirectory, StreamWriter writer)
        {
            string[] files = Directory.GetFiles(searchedDirectory);
            foreach (string fileName in files)
            {
                SearchFile(writer, fileName);
            }
            string[] directories = Directory.GetDirectories(searchedDirectory);
            foreach (string directory in directories)
            {
                SearchDirectory(directory, writer);
            }
        }

        private static void SearchFile(StreamWriter writer, string fileName)
        {
            string textToFind = "searched";
            using (StreamReader reader = File.OpenText(fileName))
            {
                int lineNumber = 0;
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    lineNumber++;
                    if (line.IndexOf(textToFind) > -1)
                    {
                        writer.WriteLine("{0:0000}: {1} - {2}", lineNumber, line, fileName);
                    }
                }
            }
        }
    }
}
